package app.book;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.ArrayList;
import java.util.List;

public class Books {
    @JsonProperty("rows") private ArrayList<Book> books;

    public Books() {
        this.books = new ArrayList<>();
    }

    public void addBook(Book book) {
        this.books.add(book);
    }

    public void delBookById(String id) {
        int index = -1;
        for (Book book: this.books) {
            if (book.getId().equals(id)) {
                index = this.books.indexOf(book);
                break;
            }
        }
        if (index >= 0) {
            this.books.remove(index);
        }
    }

    public List<Book> getBooks() {
        return this.books;
    }

    public void setBooks(ArrayList<Book> books) {
        this.books = books;
    }

    public String toJsonString() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(this);
    }

    @JsonProperty(value = "total", access = JsonProperty.Access.READ_ONLY)
    public int getTotal() {
        return this.books.size();
    }
}
